package com.analyse.stock.strategy;

import com.analyse.stock.enums.StrategyEnum;
import com.analyse.stock.exception.ServiceException;
import com.analyse.stock.model.StrategyPoolModel;
import com.analyse.stock.service.IStrategyPoolService;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class StrategyHandle {
    public static Map<String, Class<IStrategy>> strategyMap = Maps.newHashMapWithExpectedSize(10);

    private final ApplicationContext applicationContext;

    private final IStrategyPoolService strategyPoolService;

    public StrategyHandle(ApplicationContext applicationContext, IStrategyPoolService strategyPoolService) {
        this.applicationContext = applicationContext;
        this.strategyPoolService = strategyPoolService;
    }

    public IStrategy getStrategy(String strategyCode){
        StrategyPoolModel model = strategyPoolService.getStrategyPoolByCode(strategyCode);
        if(Objects.isNull(model)){
            throw new ServiceException("未查询到对应的策略:"+strategyCode);
        }
        StrategyEnum strategyEnum = StrategyEnum.getByCode(strategyCode);
        Class<IStrategy> strategyClz = strategyMap.get(strategyEnum.name());
        if(strategyClz == null){
            log.error("对应分析策略类型为空:{}",strategyCode);
            throw new ServiceException("对应分析策略类型为空:"+strategyCode);
        }
        return applicationContext.getBean(strategyClz);
    }
}
